package com.xcity.game.activity2.share.action;

import java.util.List;

import org.slf4j.Logger;

import com.xcity.Server;
import com.xcity.db.entity.Player;
import com.xcity.game.account.AccountChannel;
import com.xcity.game.activity2.share.ShareAction;
import com.xcity.game.activity2.share.ShareException;
import com.xcity.game.activity2.share.template.QQShareActivityTemplate;
import com.xcity.game.common.Cause;
import com.xcity.game.common.PlayerPool;
import com.xcity.game.event.GameEvents;
import com.xcity.game.item.ItemException;
import com.xcity.game.item.ItemInfo;
import com.xcity.game.item.ItemService;
import com.xcity.pomelo.push.msg.BatchItemsPush;
import com.xcity.pomelo.request.Share2Request;
import com.xcity.pomelo.response.Share2Response;

import gnu.trove.map.TIntObjectMap;
import naga.x.App;
import naga.x.game.template.TemplateService;
import naga.x.game.time.TimeUpdater;

/**
 * @see AccountChannel#QQ_WANBA
 * @see AccountChannel#QQ
 * @author yang.li
 *
 */
public class QQShareAction implements ShareAction {

	private QQShareActivityTemplate defaultTemplate;
	private TIntObjectMap<QQShareActivityTemplate> templatesMap;
	protected static final Logger LOG = Server.LOG;
	
	public QQShareAction() {
		templatesMap = App.getApp().getServiceManager().get(TemplateService.class).getTemplates(QQShareActivityTemplate.class);
		defaultTemplate = templatesMap.get(1); // 分享说说
	}
	
	@Override
	public Share2Response share(Player player, Share2Request req) throws ShareException {
		QQShareActivityTemplate template = templatesMap.get(req.id);
		if (template == null || !template.hasReward()) {
			return new Share2Response(req.getSerial(), req.type, req.id);
		}
		int c = getSharedCount(player, template);
		byte state = getState(player, template);
		return new Share2Response(req.getSerial(), req.type, template, state, c);
	}

	@Override
	public Share2Response reward(Player player, Share2Request req) throws ShareException {
		QQShareActivityTemplate template = templatesMap.get(req.id);
		if (template == null || !template.hasReward()) {
			return new Share2Response(req.getSerial(), req.type, req.id);
		}
		int count = getSharedCount(player, template);
		byte state = getState(player, template);
		if (state != ShareAction.STATE_CAN_REWARD) { // 分享次数已达上限
			return new Share2Response(req.getSerial(), req.type, template, ShareAction.STATE_REWARDED, count);
		}
		++count;
		addShareCount(player, template, 1);
		BatchItemsPush sync = new BatchItemsPush(2);
		if (template.getGold() > 0) {
			player.addGold(template.getGold(), Cause.SHARE_QQ);
			sync.add(ItemService.goldDefault, template.getGold());
		}
		if (template.getStone() > 0) {
			player.addStone(template.getStone(), Cause.SHARE_QQ);
			sync.add(ItemService.stoneDefault, template.getStone());
		}
		List<ItemInfo> items = template.getItemList();
		for (int i = 0; i < items.size(); i++) {
			ItemInfo item = items.get(i);
			try {
				player.getBag().addItem(item.getTemplate(), item.getCount(), Cause.SHARE_QQ);
				sync.add(item.getTemplate(), item.getCount());
			} catch (ItemException e) {
				LOG.error("[QQ SHARE REWARD ERROR]ID[" + player.getId()
						+ "]REWARD[" + template.getId()
						+ "]ITEM[" + item.getId() + "=" + item.getCount() + "]", e);
			}
		}
		player.send(sync);
		App.getApp().getEventManager().addEvent(GameEvents.EVENT_GAME_SHARE_REWARDED, player);
		LOG.info("[QQ SHARE REWARD]ID[{}]REWARD[{}]COUNT[{}]", player.getId(), template.getId(), count);
		return new Share2Response(req.getSerial(), req.type, template, ShareAction.STATE_REWARDED, count);
	}
	
	/** 今日已分享次数 */
	public static int getTodaySharedCount(Player player, QQShareActivityTemplate template) {
		String keyLastDay = PlayerPool.PROPERTY_SHARE2_LAST_DAY_PREFIX + template.getId();
		int lastDay = player.getPool().getIntValue(keyLastDay); // 上次分享日期
		if (lastDay != TimeUpdater.getInstance().today()) {
			return 0;
		}
		String keyCount = PlayerPool.PROPERTY_SHARE2_PREFIX + template.getId();
		int count = player.getPool().getIntValue(keyCount); // 今日已分享次数
		return count;
	}
	
	/** 已累计分享次数 */
	public static int getTotalSharedCount(Player player, QQShareActivityTemplate template) {
		return player.getPool().getIntValue(PlayerPool.PROPERTY_SHARE2_TOTAL_PREFIX + template.getId());
	}
	
	/** 若没有累计次数限制，则返回今日已分享次数；若有累计次数限制，则返回已累计分享次数 */
	public static int getSharedCount(Player player, QQShareActivityTemplate template) {
		if (template.getTotalCount() > 0) {
			return getTotalSharedCount(player, template);
		}
		return getTodaySharedCount(player, template);
	}
	
	/** 获取某分享任务最多可分享次数（若没有累计次数限制，则返回每日次数；若有限制，则返回累计次数） */
	public static int getMaxCount(QQShareActivityTemplate template) {
		return template.getTotalCount() > 0 ? template.getTotalCount() : template.getCount();
	}
	
	public static byte getState(Player player, QQShareActivityTemplate template) {
		if (template.getTotalCount() > 0 && getTotalSharedCount(player, template) >= template.getTotalCount()) {
			return ShareAction.STATE_REWARDED;
		}
		return getTodaySharedCount(player, template) < template.getCount() ? ShareAction.STATE_CAN_REWARD : ShareAction.STATE_REWARDED;
	}
	
	public static void addShareCount(Player player, QQShareActivityTemplate template, int c) {
		String keyLastDay = PlayerPool.PROPERTY_SHARE2_LAST_DAY_PREFIX + template.getId();
		String keyCount = PlayerPool.PROPERTY_SHARE2_PREFIX + template.getId();
		int lastDay = player.getPool().getIntValue(keyLastDay); // 上次分享日期
		int count = player.getPool().getIntValue(keyCount); // 今日已分享次数
		if (lastDay != TimeUpdater.getInstance().today()) {
			count = 0;
			player.poolSet(keyLastDay, TimeUpdater.getInstance().today());
		}
		player.poolSet(keyCount, count + 1);
		player.poolAdd(PlayerPool.PROPERTY_SHARE2_TOTAL_PREFIX + template.getId(), 1);
	}

	@Override
	public boolean isShared(Player player) {
//		return getShareCount(player, defaultTemplate) >= defaultTemplate.getCount();
		return getState(player, defaultTemplate) == ShareAction.STATE_REWARDED;
	}

}
